package mygameclient;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class CellPanel extends JPanel {

    private BufferedImage originalImage = null;
    private Image image = null;
    public float suSize;

    private boolean editable;

    public CellPanel() {
        editable = true;
        setLayout(null);
        initComponents();
        setPreferredSize(new Dimension(120, 120));
        setBackground(Color.WHITE);
        setBorder(BorderFactory.createEtchedBorder());
        setVisible(true);
    }

    @Override
    public void paint(Graphics g) {

        if (image != null) {
            g.drawImage(image, 0, 0, null);
            super.paintChildren(g);
        } else {
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, getWidth(), getHeight());
        }
        super.paintBorder(g);
    }

    public boolean isEditable() {
        return editable;
    }

    public void setEditable(boolean editable) {
        this.editable = editable;
    }

    private void initComponents() {
        setLayout(null);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });
    }

    public void clearImage(){
        this.image = null;
        this.editable = true;
        setBackground(Color.WHITE);
        repaint();
    }

    public void setImage(BufferedImage image) {
        this.originalImage = image;
        suSize = (float) (image.getWidth()) / (float) (image.getHeight());
        formComponentResized(null);
    }

    private void formComponentResized(java.awt.event.ComponentEvent evt) {
        int w = this.getWidth();
        int h = this.getHeight();
        if ((originalImage != null) && (w > 0) && (h > 0)) {
            image = originalImage.getScaledInstance(w, h, Image.SCALE_DEFAULT);
            this.repaint();
        }
    }
}
